import config from 'config';
import jwt from 'jsonwebtoken';
import { AppContext, AppState, AppConfig } from 'ROOT/interface/App';
import { outLogger } from "../common/logger";

const sign = config.get<string>('sign');
const isDev = config.get<AppConfig['env']>('env') === 'dev';
/**
 * 判断token是否可用
 */
export default async (ctx: AppContext, next: () => Promise<void> ) => {
    // 拿到token
    const authorization = ctx.get('Authorization') || ctx.session.token;

    if (!authorization) {
        if (isDev) {
            ctx.state.user = {
                user: 'test',
                id: 1,
                role: 0,
            }
            await next();
            return
        }
        ctx.sendError({ code: 401, message: 'No token detected in http header Authorization'});
        return;
    }

    try {
        const payload: AppState['user'] = jwt.verify(authorization, sign) as AppState['user'];
        ctx.state.user = {
            user: payload.user,
            id: payload.id,
            role: payload.role,
        }

        await next();
    } catch (err) {
        outLogger.error(err.message);
        ctx.sendError({ code: 401, message: 'Invalid token'});
    }

};
